<template>
  <div class="app-container">

    <!-- 搜索工作栏 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="抽奖轮盘名称" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入抽奖轮盘名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 操作工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 列表 -->
    <el-table v-loading="loading" :data="list">
      <el-table-column label="抽奖轮盘名称" align="center" prop="name" />
      <el-table-column label="轮盘图片" align="center" prop="url">
        <template v-slot="scope">
          <img style="width:50;height:50px" :src="scope.row.url" alt="">
        </template>
      </el-table-column>
      <el-table-column label="背景图片" align="center" prop="groundUrl">
        <template v-slot="scope">
          <img style="width:50;height:50px" :src="scope.row.groundUrl" alt="">
        </template>
      </el-table-column>
      <el-table-column label="轮盘类型" align="center" prop="type">
        <template v-slot="scope">
          <span>{{ tableType[scope.row.type] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="开始时间" align="center" prop="startTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.startTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="center" prop="endTime" width="180">
        <template v-slot="scope">
          <span>{{ parseTime(scope.row.endTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="剩余次数" align="center" prop="size" />
      <el-table-column label="状态" align="center" prop="status">
        <template v-slot="scope">
          <span>{{ tableStatus[scope.row.status] }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template v-slot="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)">删除</el-button>
          <el-button size="mini" type="text" @click="handleChangeUser(scope.row)">发送用户</el-button>
          <el-button size="mini" type="text" @click="handleTolottery(scope.row)">管理奖品</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件 -->
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                @pagination="getList"/>

    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="title" :visible.sync="open" width="600px" v-dialogDrag append-to-body>
      <fromcom
        ref="editForm"
        :paramsform.sync="form"
        :fromList="fromList"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 发送用户 -->
    <el-dialog :title="title" :visible.sync="useropen" width="70%" v-dialogDrag append-to-body>
      <div class="userBox">
        <myTable
          :tableList="usertableList"
          :tableColumnn="[
            {pu:true,label:'id',prop:'id'},
            {pu:true,label:'昵称',prop:'nickName'},
            {pu:true,label:'手机号',prop:'phone'},
            {pu:true,label:'邮箱',prop:'mail'},
            {img:true,label:'头像',prop:'avatar'},
            {pu:true,label:'抽奖次数',prop:'turnInfoSize'},
          ]"
          :total="usertotal"
          :showselection="true"
          :selectList.sync="selectList"
          :queryshow="true"
          :queryList="[
            {input:true,value:'id',label:'用户id'},
            {input:true,value:'phone',label:'手机号'},
            {input:true,value:'mail',label:'邮箱'},
          ]"
          :paramsform.sync="queryment"
          @gettabledata="getUserInfo"
        ></myTable>

        <div class="changeBox">
          <div class="title" @click="deleteAll"><span>全部删除</span></div>
          <div class="content">
            <div class="item" v-for="(item,index) in changeList" :key="item.id"><p class="name">{{item.nickName}} </p><span @click="changeList.splice(index,1)">删除</span></div>
          </div>
        </div>
      </div>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="userSubmitForm">确 定</el-button>
        <el-button @click="useropen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { createTurntable, updateTurntable, deleteTurntable, getTurntable, getTurntablePage, exportTurntableExcel } from "@/api/qd/turntable";
import { getUserPage } from "@/api/qd/user";
export default {
  name: "Turntable",
  components: {
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 转盘管理列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        createTime: [],
        name: null,
        url: null,
        type: null,
        startTime: [],
        endTime: [],
        size: null,
        status: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      fromList:[
        {input:true,value:'name',label:'抽奖轮盘名称'},
        {upload:true,value:'url',label:'轮盘图片',limit:1},
        {uploadTwo:true,value:'groundUrl',label:'背景图片',limit:1},
        {select:true,value:'type',label:'轮盘类型',list:[{ value:1,label:'普通轮盘'},{ value:2,label:'注册轮盘'},{ value:3,label:'拼团轮盘'},]},
        {data:true,value:'startTime',label:'开始时间'},
        {data:true,value:'endTime',label:'结束时间'},
        {input:true,value:'size',label:'剩余次数'},
        {radio:true,value:'status',label:'状态',list:[{value:1,label:'开启'},{value:2,label:'关闭'}]},
      ],
      tableType:{1:'普通轮盘',2:'注册轮盘',3:'拼团轮盘'},
      tableStatus:{1:'开启',2:'关闭'},
      // 用户选择列表
      useropen:false,
      usertableList:[],
      usertotal:0,
      selectList:[],
      queryment:{},
      changeList:[], // 选中的用户
    };
  },
  created() {
    this.getList();
  },
  watch:{
    'form.type':{
      handler(){
        const index = this.returnIndex('startTime',this.fromList)
        // if(this.form.type == 2 && !index){
        //    const index3 = this.returnIndex('size',this.fromList)
        //    this.fromList.splice(index3,0,{data:true,value:'startTime',label:'开始时间'})
        //    this.fromList.splice(index3+1,0,{data:true,value:'endTime',label:'结束时间'})
        // }
        // if((this.form.type == 1 || this.form.type == 3) && index){
        //   this.fromList.splice(index,1)
        //   const index2 = this.returnIndex('endTime',this.fromList)
        //   this.fromList.splice(index2,1)
        // }
      }
    },
    selectList (newValue, oldValue){
      let arr =  newValue.map(item=>{
        if(this.changeList.length == 0) return item
        if(!this.changeList.some(i=>i.id === item.id))return item
      }).filter((ite) => typeof ite !== 'undefined')
      this.changeList = this.changeList.concat(arr ?? [])
    },
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 执行查询
      getTurntablePage(this.queryParams).then(response => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        name: undefined,
        url: undefined,
        type: undefined,
        startTime: undefined,
        endTime: undefined,
        size: undefined,
        status: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加转盘管理";
    },
    returnIndex(value,arr){
      let inde=null
      arr.forEach((item,index)=>{
        if(value === item.value){
          inde=index
        }
      })
      return inde
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getTurntable(id).then(response => {
        this.form = response.data;
        if(this.form.url) this.$set(this.form,'filelist',[{url:this.form.url}])
        if(this.form.groundUrl) this.$set(this.form,'filelistTwo',[{url:this.form.groundUrl}])
        this.open = true;
        this.title = "修改转盘管理";
      });
    },
    handleTolottery(row){ // 前往奖品管理页面
      this.$router.push({path:'/lottery/lottery',query:{id:row.id,type:'turntable'}})
    },
    handleChangeUser(row){
      this.form = {...row}
      this.changeList = []
      this.getUserInfo()
    },
    deleteAll(){
      this.$confirm('是否确定删除全部?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.changeList = []
        })
    },
    getUserInfo(params={pageNo: 1,pageSize: 10}){ // 获取用户数据
      getUserPage(params).then(response => {
        this.usertableList = response.data.list;
        this.usertotal = response.data.total;
        this.useropen = true
      });
    },
    userSubmitForm(){ //发送用户 提交
      if(this.changeList.length == 0) return this.$message.warning('请先选择用户')
      const data = {
        ids:this.changeList.map(item=>item.id),
        id:this.form.id
      }
      this.$axios({url:'/qd/turntable/toUser',method:'post',data}).then(res=>{
        this.$message.success('操作成功')
        this.useropen = false
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['editForm'].$refs['form'].validate(valid => {
        if (!valid) {
          return;
        }
        // 修改的提交
        if (this.form.id != null) {
          updateTurntable(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        createTurntable(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal.confirm('是否确认删除转盘管理编号为"' + id + '"的数据项?').then(function() {
          return deleteTurntable(id);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = {...this.queryParams};
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.$modal.confirm('是否确认导出所有转盘管理数据项?').then(() => {
          this.exportLoading = true;
          return exportTurntableExcel(params);
        }).then(response => {
          this.$download.excel(response, '转盘管理.xls');
          this.exportLoading = false;
        }).catch(() => {});
    }
  }
};
</script>
<style scoped lang="scss">
.el-dialog{
  position: relative;
  .changeBox{
    position: absolute;
    z-index: 1000;
    top: 0%;
    right: -200px;
    width: 200px;
    // height: 350px;
    height: 100%;
    border: 1px solid #ccc;
    border-radius: 10px;
    // overflow: hidden;
    .title{
      background: rgb(209, 210, 210);
      height: 50px;
      white-space: nowrap;
      padding: 10px;
      cursor: pointer;
    }
    .content{
      // height: 300px;
      height: calc(100% - 50px);
      overflow-y: scroll;
      padding: 10px;
      background: rgba(245, 247, 250,1);
      .item{
        display: flex;
        align-items: center;
        white-space: nowrap;
        .name{
          width: 140px;
          overflow: hidden;
          white-space: nowrap;
          text-overflow: ellipsis;
        }
        span{
          color: #fe6d6d;
          cursor: pointer;
        }
      }
    }
  }
}
</style>
